package books4africa

import grails.plugins.springsecurity.*
import org.springframework.dao.DataIntegrityViolationException
import org.codehaus.groovy.tools.shell.commands.RegisterCommand
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails

class DonorController {
    
	def userDetailsService
	def springSecurityService 
    def scaffold = true

    def index() {
        redirect(action: list)
    }

	def currentUser(){
		Donor.get(springSecurityService.principal.id)
	
	}
	
    def login = { }
	
    def doLogin = {
		def donor= Donor.findWhere(username:params['username'],
			password:params['password'])
			session.donor = donor
			
			
		UserDetails userDetails =  userDetailsService.loadUserByUsername('username', true)
			println="user datails = $userDetails"
			 
	
		if(donor){
		//	redirect(uri: "/profile/profileView", params: donor); 
			redirect(controller: 'profileView',action: 'view', params: [name: session.name])
		}else{
		//flash.message= "Invalid login"
		//return [donor: donor ]
			redirect(uri: "/");
	}
		
  }
	
	def register = { 
		if(!params.register) return
		
		def role = Role.findByAuthoruty("ROLE_USER")
		if(!role){
			donor.password = null
			flash.message = "Default Role not found."
			return
		}
		//if user has errors
		//if user is not saved
		UserRole.create donor, role
		
    }
	def changePassword = {
		if(!params.submit){
//			def donor = Donor.findByUsername(params.username)
			return [donor: currentUser()]
		}
		String pass1 = params.password
		String pass2 = params.repeatPassword
		def donor = currentUser()
		if(pass1 != pass2){
			donor.password = ""
			flash.message = "Error: Passwords Did Not Match"
			//return [donor: params]
		}
		donor.password = pass1
		if(donor.validate()){
			donor.save()
			redirect(controller: "login", action: "auth", params: [username: donor.username])
		}else{
			donor.password = ""
			return [donor: donor]
		}
	}
	
}//end of controller


